# -*- coding: utf-8 -*-
# @Time: 2021/11/5 21:08
# @Author: jiuwu
# @Email: 2359196586@qq.com
# @File: serializers.py
# @Software: PyCharm
from rest_framework.serializers import ModelSerializer
from .models import Classes
from users.serializers import UserSerializer
from rest_framework.fields import SerializerMethodField


class ClassesSerializer(ModelSerializer):
    memberDetail = SerializerMethodField()

    class Meta:
        model = Classes
        exclude = ['is_delete']

        # 将member设置成已写，就不会出现在前端页面了，但是不能不映射
        extra_kwargs = {
            'member': {'write_only': True}
        }

    def get_memberDetail(self, classes):
        # 通过member查询得到该班级所有学生数据 然后进行序列化
        serializer = UserSerializer(classes.member.all(), many=True)
        data = {
            # is_staff 是否能登录后台管理系统
            'teacher': [i for i in serializer.data if i['is_staff'] == True or 2 in i['groups']],
            'student': [i for i in serializer.data if 1 in i['groups']]
        }
        return data
